/**
 *  版权所有 Copyright@2016年3月16日下午6:01:49
 */
package com.fairy.sso.server.filter;
/**
 * [SSOServerFilter.java.java]
 *
 * @Author: [yyk1504@163.com]
 * @CreateDate: [2016年4月6日下午6:01:49]
 * @Update: [说明本次修改内容] by [yyk1504@163.com] [2016年3月16日下午6:01:49]
 * @Version: [v1.0]
 */
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import com.fairy.core.util.NetUtil;
import com.fairy.sso.cache.SSOCache;
import com.fairy.sso.config.FairyConfig;
import com.fairy.sso.core.CookieHelper;
import com.fairy.sso.core.NetHelp;
import com.fairy.sso.core.SSOConstants;
import com.fairy.sso.core.Ticket;
import com.fairy.sso.server.Factory;
import com.fairy.sso.server.SSOCacheFactory;

public class SSOServerFilter implements Filter {
	@Autowired(required=true)
	private FairyConfig fairyConfig;
	//private ServletContext  servletContext; 
	//private ApplicationContext applicationContext;  
	
	//@Autowired(required=true)
	//private SSOService<SSOUserEntity> ssoService;
	private static Logger log = Logger.getLogger(SSOServerFilter.class);
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //HttpServletResponse response = (HttpServletResponse) servletResponse;
        
        log.info("来自["+request.getContextPath()+"]的请求");
        
        String cookieValue=CookieHelper.getCookieValueByName(request, SSOConstants.SSO_COOKIE_KEY);
        log.info("cookieValue is::"+cookieValue);
        
        String domain=NetHelp.getDomain(request);
        log.info("domain is::"+domain);
        
        String Agent = request.getHeader("User-Agent");  
        log.info("Agent  is::"+Agent);

        
        //String service = request.getParameter(SSOConstants.CLIENT_URL);
		String requestUri = request.getRequestURI();
		String contextPath=request.getContextPath();
		requestUri=requestUri.replace(contextPath, "");
		//List<String>noCheckUrlList=SSOConstants.noCheckUrlList;
		//noCheckUrlList.add("/index.do");
		//noCheckUrlList.add("/login.do");
		//noCheckUrlList.add("/logout.do");
		//noCheckUrlList.add("/ticket.do");
		
        if (null != cookieValue && !"".equals(cookieValue)) 
        {  
        	//验证cookies是否被篡改
        	//ObjectMapper mapper = new ObjectMapper(); 
    		Ticket t = getTicket(cookieValue);
    		
        	if(null!=t)
        	{
        		log.info("ticket中保存的Ip地址:"+t.getIp());
    			log.info("Ticket is::"+t.toString());
    			verify(servletRequest, servletResponse, filterChain, request, t);
    			log.info("Ticket is::"+t.toString());      	
        	}
        	else
        	{
        		filterChain.doFilter(servletRequest, servletResponse);  
        	}         

        } 
        else 
        {  
        	log.info("cookieValue is null");
        	String key = request.getParameter("ticket");
        	if(null!=key)
        	{
            	Ticket t = getTicket(key);
            	if(null!=t)
            	{
        			log.info("Ticket is::"+t.toString());
        			verify(servletRequest, servletResponse, filterChain, request, t);
            	}
            	else
            	{
            		filterChain.doFilter(servletRequest, servletResponse);  
            	}
        	}
        	else
        	{
        		log.info("Ticket key is nul");
        		filterChain.doFilter(servletRequest, servletResponse);  
        	}

            
        }
      	
    }

	private void verify(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain,
			HttpServletRequest request, Ticket t) throws IOException, ServletException {
		String  ip=NetUtil.getIpAddr(request);
		log.info("本次请求的ip地址:"+ip);
		if(ip.equals(t.getIp()))
		{
			log.info("验证cookies是否被篡改,ip验证通过");
			filterChain.doFilter(servletRequest, servletResponse);
		}
		else
		{
			log.info("验证cookies是否被篡改,ip验证未通过");
			//转到错误页面
			filterChain.doFilter(servletRequest, servletResponse);
		}
	}

	private Ticket getTicket(String cookieValue) {
		Ticket t =null;
		Factory factory = new SSOCacheFactory(); 
		String cacheType=fairyConfig.getCacheType();
		SSOCache cache = factory.createSSOCache(cacheType); 
		t=cache.get(cookieValue);
		/**
		if(null==t)
		{
			//重新从数据库或者缓存加载ticket
			t=ssoService.loadTicket(cookieValue);
			cache.set(cookieValue,t);
			log.info("ticket 重新加载并保存到缓存中:"+t);
		}*/
		return t;
	}



    @Override
    public void init(FilterConfig config) throws ServletException {
    	//servletContext =config.getServletContext(); 
    	//super.init(config); 
    	SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());  
    	//applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);  
    	//fairyConfig = (FairyConfig) applicationContext.getBean("fairyConfig"); 
    }

}